package com.macro.mall.service.impl;

import com.macro.mall.dto.FileUploadDto;
import com.macro.mall.service.CosService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class CosServiceImpl implements CosService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CosServiceImpl.class);

    @Autowired
    private COSClient cosClient;

    @Value("${cos.bucketName}")
    private String bucketName;

    @Value("${cos.region}")
    private String region;

    @Override
    public FileUploadDto upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new RuntimeException("文件名不能为空");
            }

            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateStr = sdf.format(new Date());
            String fileName = dateStr + "/" + UUID.randomUUID().toString() + extension;

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            objectMetadata.setContentType(file.getContentType());

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream(), objectMetadata);
            cosClient.putObject(putObjectRequest);

            LOGGER.info("文件上传成功: {}", fileName);

            // 只返回文件路径，不包含签名参数
            String url = String.format("https://%s.cos.%s.myqcloud.com/%s", bucketName, region, fileName);

            FileUploadDto result = new FileUploadDto();
            result.setName(originalFilename);
            result.setUrl(url);
            return result;

        } catch (IOException e) {
            LOGGER.error("文件上传失败: {}", e.getMessage());
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Override
    public boolean delete(String objectName) {
        try {
            cosClient.deleteObject(bucketName, objectName);
            LOGGER.info("文件删除成功: {}", objectName);
            return true;
        } catch (Exception e) {
            LOGGER.error("文件删除失败: {}", e.getMessage());
            return false;
        }
    }
}